/**
 * 长任务监控（主线程阻塞 >100ms）
 * 基于 Long Tasks API
 */
type LongTaskMetric = {
    duration: number
    startTime: number
    taskType: string
    pageState: string
    blockingTime?: number
    time: number
}

export function trackLongTasks(report: (data: LongTaskMetric) => void) {
    if (typeof window === "undefined" || !("Performance" in window)) return

    let lastReportTime = 0
    const DEBOUNCE_INTERVAL = 5000
    const SAMPLE_RATE = 1 // 采样率

    const observer = new PerformanceObserver(list => {
        list.getEntries().forEach(entry => {
            // 基础过滤：只处理超过100ms的任务
            if (entry.duration <= 100) return

            // 采样控制：随机上报20%
            if (Math.random() > SAMPLE_RATE) return

            // 防抖控制：5秒内不重复上报相似任务
            const now = Date.now()
            if (now - lastReportTime < DEBOUNCE_INTERVAL) return

            report({
                duration: parseFloat(entry.duration.toFixed(2)),
                startTime: parseFloat(entry.startTime.toFixed(2)),
                // 超过100ms时间
                blockingTime: parseFloat(Math.max(entry.duration - 100, 0).toFixed(2)),
                taskType: entry.name.includes("Event") ? "event" : "script",
                pageState: document.visibilityState,
                time: now
            })
            lastReportTime = now
        })
    })
    observer.observe({ type: "longtask", buffered: true })
}
